# -*- coding: utf-8 -*-

from qgis.core import (
    QgsGeometry,
    QgsWkbTypes,
    Qgis
)

from qgis.gui import (
    QgsMapToolEmitPoint,
    QgsRubberBand,
    QgsMapMouseEvent
)

from typing import Optional

from PyQt5.QtCore import (
    Qt,
    pyqtSignal
)

class DrawPointTool(QgsMapToolEmitPoint):
    # 绘制信号
    # str 绘制行为
    # Qgis.GeometryType 绘制类型
    # QgsGeometry 绘制图形容器
    drawGeometry = pyqtSignal(str,Qgis.GeometryType,QgsGeometry)
    
    def __init__(self,action, canvas):
        super().__init__(canvas)
        self.__action = action
        self.__canvas = canvas
        self.__point_rubber_band = QgsRubberBand(canvas, QgsWkbTypes.PointGeometry)
        self.__point_rubber_band.setColor(Qt.blue)
        self.__point_rubber_band.setWidth(2)


    def canvasPressEvent(self, e):
        # e.isAccepted() 验证按钮是否被接收，添加了此判断之后勾绘会有卡顿
        #if e.button() == Qt.LeftButton and e.isAccepted():
        if e.button() == Qt.LeftButton:

            # 将鼠标点击位置转换为geometry点
            geometry = QgsGeometry().fromPointXY(e.mapPoint())

            # # 获取当前地图画布的坐标参考系统
            crs = self.__canvas.mapSettings().destinationCrs()

            # 将geometry写入到容器rubber_band中
            self.__point_rubber_band.setToGeometry(geometry, crs)

            # 将数据发送到信号中
            self.drawGeometry.emit(self.__action, Qgis.GeometryType.Point, geometry)

            # 重置图形
            self.__point_rubber_band.reset(QgsWkbTypes.PointGeometry)

    def deactivate(self):
        del self.__point_rubber_band
        super().deactivate()

